<template>
  <div>
    <div class="warning" v-show="isWeixin">
      <div>请复制下方链接或点击右上角直接在手机浏览器内打开</div>
      <div>{{href}}</div>
    </div>
    <div v-show="!isWeixin">
      <canvas id="cvs" width="375" height="667"></canvas>
      <!-- bar -->
      <header class="header">
        <img @click="back" class="back" src="../assets/back-icon.png" alt="<" />
        <span class="title">绿电溯源证书</span>
        <span @click="share" class="share">{{showShareBtn ? '分享' : '    '}}</span>
      </header>
      <!-- <img class="export" id="export" src="../assets/export.png" alt="ttt" /> -->
      <div class="page1">
        <div class="wrapper">
          <div class="main">
            <div class="inner">
              <div class="box">
                <!-- 圆圈 -->
                <div :style="{ background: `url('${avaterMap[info.type || 1]}')` }" class="avatar">
                </div>
                <!-- 证书标题 -->
                <img class="title" src="../assets/title.png" alt="区块链绿电溯源证书" />
                <!-- 电力流向 -->
                <div class="formTo">
                  <div>
                    <div class="formToTitle">发电省</div>
                    <div class="fromToDesc">{{info.genProvince}}</div>
                  </div>
                  <div>
                    <div class="formToTitle">受电省</div>
                    <div class="fromToDesc">{{info.receiveProvince}}</div>
                  </div>
                </div>
                <!-- 绿电通证 -->
                <div class="infoWrapper">
                  <div class="greenPass">
                    <div class="label">绿电通证</div>
                    <div class="greenPassNumber">
                      <span class="number">{{info.miniId}}</span>
                      <span @click="showPopup" class="btn">查看完整通证</span>
                    </div>
                    <div>
                      <span class="label">绿电类型</span>
                      <span class="font">{{info.typeName}}</span>
                    </div>
                    <!-- <div>
                      <span class="label">调度哈希</span>
                      <span class="font">{{info.contractTxHashFormat}}</span>
                      <span style="float:right" @click="showPopup2" class="btn">查看完整通证</span>
                    </div> -->
                    <div>
                      <span class="label">通证生成时间</span>
                      <span class="font">{{info.certificateCreateTimeFormat}}</span>
                    </div>
                    <!-- <div>
                      <span class="label">运营商编号</span>
                      <span class="font">{{info.operatorId}}</span>
                    </div>
                    <div>
                      <span class="label">运营商名称</span>
                      <span class="font">{{info.operatorName}}</span>
                    </div> -->
                  </div>
                </div>
                <!-- 底部声明 -->
                <div class="bottomInfo">
                  <div>本溯源证书内数据皆源于绿电实际上链的记录</div>
                  <div>由区块链技术保证数据真实可靠，任何人或机构无法篡改</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 底部 -->
        <!-- <div class="bottom">
          <img src="../assets/icon-up.png" alt="up" class="upIcon">
          <div class="bottomDesc">上划查看溯源详情</div>
        </div> -->
        <page-second :info="info" />
      </div>
      
      <div id="qrcode"></div>
      <!-- 弹窗 -->
      <van-popup class="dialog" v-model="visible">{{info.id}}</van-popup>
      <van-popup class="dialog" v-model="visible2">{{info.contractTxHash}}</van-popup>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import PageSecond from '@/components/PageSecond.vue'
import jsBridge from '../utils/jsBridge'
import isWeixin from '../utils/isWeixin'
// import html2canvas from 'html2canvas'
import base64Str from '../components/base64'
import { parse } from 'querystring'
import canvasBg from '../assets/canvas-bg.png'
import fengImg from '../assets/canvas-feng.png'
import shuiImg from '../assets/canvas-shui.png'
import guangImg from '../assets/canvas-guang.png'
import avater1 from '../assets/type-1.png'
import avater2 from '../assets/type-2.png'
import avater3 from '../assets/type-3.png'
import qrCodeImg from '../assets/qrCode.png'
import dayjs from 'dayjs'
import { Indicator } from 'mint-ui'

export default {
  name: 'Home',
  components: {
    PageSecond
  },
  created () {
    // jsBridge.NativeNetworkRequest({
    //   url: 'internal.validationTokens',
    //   method: 'post',
    //   params: {
    //     token: 'c:app:67F1510767DC46CDB8DCAF6ABD99856A',
    //     greenElectricCode: '11111111111'
    //   }
    // })
  },
  mounted () {
    // 数据
    jsBridge.SetTitleBar({
      isShow: false
    })
    // console.log(parse(location.search.replace('?', '')))
    const code = parse(location.search.replace('?', '')).code
    jsBridge.getToken((res) => {
      // console.log('getToken: ---> ' + res)
      jsBridge.NativeNetworkRequest({
        ua: 'E卡',
        url: 'internal.validationTokens',
        encryption: '1',
        method: 'post',
        params: `{"token":"${res}","greenElectricCode":"${code}"}`
      }, (res) => {
        console.log(res);
        const result = JSON.parse(res || "{}")
        if (result && result.data && result.data.code === 1) {
          this.setInfo(result.data.data || {}, code)
          this.$data.showShareBtn = true
        }
        // console.log('NativeNetworkRequest: ---> ', JSON.stringify(res))
      })
    })
    
    // const cvs = document.getElementById('cvs')
    // const ctx = cvs.getContext('2d')
    // this.$data.ctx = ctx
    // this.createCanvas()

    // schema 打开
    if (!this.isWeixin) {
      const { origin, host, pathname, search } = location
      const queryParams = parse(search.replace('?', ''))
      const { goDownloadPage, code } = queryParams
      // console.log(`echargeapp://${host}${pathname}?code=${code}`)
      if (goDownloadPage) {
        location.href = `echargeapp:///apptab/selected?index=0`
        // console.log(`echargeapp://${host}${pathname}?code=${code}`)
        setTimeout(() => {
          location.href = 'http://www.echargenet.com/portal/csService/html/app.html'
        }, 500)
      }
    }
  },
  methods: {
    // 画布
    createCanvas () {
      Indicator.open()
      const { ctx } = this
      const { drawFont } = this

      const { info } = this.$data
      
      // 背景
      const bg = new Image()
      bg.src = canvasBg
      bg.onload = () => {
        ctx.drawImage(bg, 0, 0, 375, 667);


        // from
        drawFont({
          text: info.genProvince,
          x: 56.77,
          y: 266.49,
          fontSize: 16,
          color: '#F7F4EC'
        })
        // to
        drawFont({
          text: info.receiveProvince,
          x: 267.9,
          y: 266.49,
          fontSize: 16,
          color: '#F7F4EC'
        })

        // 绿电通证
        drawFont({
          text: info.miniId,
          x: 74,
          y: 331,
          fontSize: 14,
          color: '#333333'
        })

        // 类型
        drawFont({
          text: info.typeName,
          x: 162,
          y: 371,
          fontSize: 12,
          color: '#333333'
        })

        // 哈希
        drawFont({
          text: info.contractTxHashFormat,
          x: 162,
          y: 391,
          fontSize: 12,
          color: '#333333'
        })

        // 时间
        drawFont({
          text: info.certificateCreateTimeFormat,
          x: 162,
          y: 413,
          fontSize: 12,
          color: '#333333'
        })

        // 编号
        drawFont({
          text: info.operatorId,
          x: 162,
          y: 434,
          fontSize: 12,
          color: '#333333'
        })

        // 名称
        drawFont({
          text: info.operatorName,
          x: 162,
          y: 454,
          fontSize: 12,
          color: '#333333'
        })

        
        // 二维码
        // const codeWrapper = document.getElementById("qrcode")
        // const { host, pathname, search } = window.location
        // let codeText = `http://${host}${pathname}?goDownloadPage=1`
        // // 二维码在192-220区间没办法支持，规避做法
        // if (codeText.length >= 192 || codeText.length <= 220) {
        //   codeText += '&useless=nnnnnnnnnnnnnnnnnnn'
        // }
        // new QRCode(codeWrapper, {
        //   text: 'https://cdn-evone-oss.echargenet.com/resource/static/share/index.html',
        //   // text: 'http://evone-test.sodoulala.com/dist/index.html?code=421220ac9bb83094b8bafcae2f00012851c0df23bad19ddcf86339ad371e752de1690x4ed2a61c500e0d70e3937d7d5a716a8118e3d684aee0ef5abed1bd0c71c9c0871&no=nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn',
        //   width: 112,
        //   height: 112,
        //   colorDark : "#4A8A68",
        //   colorLight : "#ffffff",
        //   correctLevel : QRCode.CorrectLevel.H
        // })
        // 电类型
        const typeMap = {
          '风电': fengImg,
          '光电': guangImg,
          '水电': shuiImg
        };
        const typeImg = new Image();
        typeImg.src = typeMap[info.typeName] || fengImg;
        console.log(typeMap[info.typeName] || fengImg)
        const positionX = 118;
        const positionY = 54.16;
        typeImg.onload = () => {
          setTimeout(() => {
            ctx.drawImage(typeImg, positionX, positionY, 140, 133);
            // this.$data.showShareBtn = true
            // ctx.drawImage(codeWrapper.getElementsByTagName('img')[0], 132, 484, 112, 112)
            // console.log(base64Str)
            const canvas = document.getElementById('cvs')
            // console.log(canvas.toDataURL('image/png', 0.7))
            Indicator.close();
            jsBridge.ShareEvent({
              title: 'test',
              url: 'test',
              imageUrl: canvas.toDataURL('image/png', 0.7),
              // imageData: base64Str,
              // imageUrl: base64Str,
              type: 2
            })
          }, 500)
        }
        // 放入qrCode
        const qrCode = new Image()
        qrCode.src = qrCodeImg
        qrCode.onload = () => {
          ctx.drawImage(qrCode, 132, 484, 112, 112)
        }
      }
    },
    showPopup () {
      this.visible = true
    },
    showPopup2 () {
      this.visible2 = true
    },
    // 文字
    drawFont ({ x, y, fontSize, color, text }) {
      const { ctx } = this
      ctx.fillStyle = color
      ctx.font = `${fontSize}px  Noto Sans SC`
      ctx.textAlign = 'left'
      ctx.textBaseline = 'top'
      ctx.fillText(text, x, y)
    },
    back () {
      jsBridge.turnback()
    },
    share () {

      const cvs = document.getElementById('cvs')
      const ctx = cvs.getContext('2d')
      this.$data.ctx = ctx
      this.createCanvas()
      // html2canvas(document.getElementById('export')).then(function (canvas) {
      //   jsBridge.ShareEvent({
      //     title: 'test',
      //     url: 'test',
      //     // imageData: canvas.toDataURL('image/png', 1).replace('data:image/png;base64,', ''),
      //     imageData: base64Str,
      //     type: 2
      //   })
      // })
    },
    setInfo (info, code) {
      let id = ''
      let contractTxHashFormat = ''
      let certificateCreateTimeFormat = ''
      if (typeof info.contractTxHash === 'string') {
        contractTxHashFormat = `${info.contractTxHash.slice(-8)}******${info.contractTxHash.slice(0, 8)}`
      }

      if (typeof code === 'string') {
        id = `${code.slice(0, 10)}******${code.slice(-10)}`
      }

      if (info.certificateCreateTime) {
        certificateCreateTimeFormat = dayjs(info.certificateCreateTime).format('YYYY年MM月DD日 HH:mm:ss')
      }

      // 电类型
      const typeMap = {
        '风电': fengImg,
        '光电': guangImg,
        '水电': shuiImg
      };
      
      this.$data.info = {
        ...info,
        id: code,
        miniId: id,
        contractTxHashFormat,
        certificateCreateTimeFormat,
        typeImg: typeMap[info.typeName] || fengImg
      }
    }
  },
  data: () => {
    return {
      ctx: null,
      options: {
      },
      visible: false,
      visible2: false,
      info: {
        // genProvince: '123'
        // typeName: '水电'
      },
      isWeixin: isWeixin(),
      href: window.location.href,
      avaterMap: {
        1: avater1,
        2: avater2,
        3: avater3,
      },
      showShareBtn: false
    }
  }
}
</script>
<style scoped lang="less">
  .dialog {
    padding: 20px;
    font-size: 12px;
    word-break: break-all;
  }
  .warning {
    margin-top: 40%;
    padding: 20px;
    font-size: 20px;
    word-break: break-all;
  }
  #cvs {
    position: fixed;
    z-index: 1000;

    left: 500px;
    top: 300px;
    // left: 0;
  }
  #qrcode {
    display: none;
  }
  .header {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    height: 42px;
    background: #FFFFFF;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 12px 0 18px;
    z-index: 1000;
    color: rgba(0, 0, 0, 0.8);
    .back {
      width: 24px;
      height: 24px;
    }
    .title {
      font-size: 18px;
    }
    .share {
      font-size: 16px;
    }
  }
  .page1 {
    background: url('../assets/bg1.png') no-repeat;
    background-color: #DBE8E1;
    background-size: 100% auto;
    background-position-y: 42px;
    border-top: 1px solid #DBE8E1;
    font-family: Noto Sans SC;
    position: relative;
    .bottom {
      position: absolute;
      bottom: 24px;
      left: 0;
      right: 0;
      height: 44px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      .upIcon {
        width: 14px;
        height: 18px;
      }
      .bottomDesc {
        font-size: 12px;
        line-height: 14px;
        color: #4A8A68;
        opacity: 0.5;
        transform: scale(10 / 12);
      }
    }
    .wrapper {
      margin-top: 229px;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .main {
        height: 424px;
        width: 347px;
        .inner {
          height: 344px;
          box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.1);
          background: #FFFFFF;
          padding: 8px;
          border-radius: 8px;
          position: relative;
          .box {
            border: 1px solid #C0DFD1;
            height: 100%;
            border-radius: 8px;
            .avatar {
              width: 154px;
              height: 154px;
              border-radius: 50%;
              border: 8px solid #4A8A68;
              position: absolute;
              left: 50%;
              transform: translateX(-50%);
              top: -112px;
              // background: url('../assets/page2-img-1.png');
              background-size: 100%;
            }
            .title {
              margin-top: 8px;
              position: relative;
              z-index: 100;
              width: 288px;
              height: 63px;
            }
            .formTo {
              background: url('../assets/from-to.png') no-repeat;
              background-size: 100% 100%;
              width: 260px;
              height: 50px;
              margin: 6px auto 0;
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 0 20px;
              .formToTitle {
                color: rgba(255, 255, 255, .4);
                font-size: 12px;
                line-height: 17px;
              }
              .fromToDesc {
                font-size: 16px;
                line-height: 23px;
                color: #F7F4EC;
              }
            }
            .infoWrapper {
              padding: 0 20px;
            }
            .greenPass {
              margin-top: 20px;
              text-align: left;
              font-size: 12px;
              .greenPassNumber {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 20px;
                .number {
                  font-weight: 500;
                  font-size: 14px;
                  line-height: 20px;
                  color: #333333;
                }
              }
            }
            .btn {
              font-size: 10px;
              line-height: 14px;
              color: #4A8A68;
            }
            .label {
              font-size: 12px;
              line-height: 17px;
              margin-bottom: 4px;
              color: #999999;
              text-align: left;
              width: 88px;
              display: inline-block;
            }
            .font {
              color: #333333;
              font-size: 12px;
              line-height: 17px;
            }
          }
          .bottomInfo {
            margin-top: 48px;
            font-size: 12px;
            color: #ccc;
            transform: scale(0.67);
          }
        }
      }
    }
  }
</style>
